/**
 * 
 */
package us.gaaoc.framework.webapp.backingbeans.filingSearch;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.FilingSearch;
import us.gaaoc.framework.model.util.DataPage;
import us.gaaoc.framework.model.util.PagedListDataModel;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;

/**
 * @author Sukhada 
 * <!--
 * 	May 26, 2006 
 * 	GAJE_BibbCounty_1.0
 * <br/>
 * <br/>
 *  Edited by Brandon Denney
 * 	2008/05/19
 * <br/>
 * 	<p>Revisions page the search result data.</p>
 * -->
 * 
 * The backing bean for the searchResultPage.xhtml.
 */
@SuppressWarnings("unchecked")
public class SearchResults extends BaseBackingBean {

	/* **************** *
	 * Global variables *
	 * **************** */
	
	/** Generated Serial Version UID */
	private static final long serialVersionUID = 2757949045384370023L;
	/** The data model that holds the information for the data
	 *  table being displayed. */
	private DataModel results;
	/** A number representing the number of entries in the data table
	 *  to be expected. Used for paging the data table. */
	private int resultsCount;
	/**
	 * property searchWord
	 */
	private String searchWord;
		
	private boolean errorMessage;

	private List<Documents> documentList;
	
	Logger LOG  = Logger.getLogger(SearchResults.class);
	
	/* ******* *
	 * Getters *
	 * ******* */
	
	/**
	 * Getter for the results data model.
	 * 
	 * @return the data model containing the requested search results.
	 */
	public DataModel getResults() {
		results = new ResultsDataModel(10);
		return results;
	}
	
	/**
	 * Getter for the resultsCount integer.
	 * 
	 * @return the number of results that were produced by the search string.
	 */
	public int getResultsCount() {
		resultsCount = this.getResults().getRowCount();
		return resultsCount;
	}
	
	/**
	 * @return Returns the documentList.
	 */
	public List<Documents> getDocumentList() {
		return documentList;
	}
	
	/**
	 * @return Returns the searchWord.
	 */
	public String getSearchWord() {
		return searchWord;
	}
	
	/**
	 * Getter for the errorMessage flag.
	 * 
	 * @return the flag indicating if an error message should be shown.
	 */
	public boolean getErrorMessage() {
		return this.errorMessage;
	}
	
	/* ******* *
	 * Setters *
	 * ******* */
	
	/**
	 * Setter for the results data model.
	 * 
	 * @param results a data model representing the search results to be 
	 * shown in the data table.
	 */
	public void setResults(DataModel results) {
		this.results = results;
	}
	
	/**
	 * Setter for the resultsCount integer.
	 * 
	 * @param resultsCount the number of results that were produced by the
	 * search string.
	 */
	public void setResultsCount(int resultsCount) {
		this.resultsCount = resultsCount;
	}
	
	/**
	 * @param documentList The documentList to set.
	 */
	public void setDocumentList(List<Documents> documentList) {
		this.documentList = documentList;
	}
	
	/**
	 * @param errorMessage the errorMessage to set
	 */
	public void setErrorMessage(boolean errorMessage) {
		this.errorMessage = errorMessage;
	}
	
	/**
	 * @param searchWord
	 *            The searchWord to set.
	 */
	public void setSearchWord(String searchWord) {
		this.searchWord = searchWord;
	}

	/**
	 * Default Constructor.
	 */
	public SearchResults() {
		results = new ListDataModel();			
	}

	/**
	 * @return the errorMessage
	 */
	public boolean isErrorMessage() {
		return false;
	}

	/**
	 * This method gets called when the user views the PDF document
	 * @return
	 * @throws Exception
	 */
	public String viewAttachment() throws Exception {
		Map requestMap = this.getFacesContext().getExternalContext()
				.getRequestParameterMap();
		HttpServletResponse resp = (HttpServletResponse) this.getFacesContext()
										.getExternalContext().getResponse();
		String docTitle = (String) requestMap.get("title");
		String uuid = (String)requestMap.get("uuid");
		String courtUuid = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("courtUuid");
		CaseRecord c = this.getModelFacade().findCaseRecordById(uuid, courtUuid);
		
		this.documentList = c.getDocuments();
		byte[] docContent = null;
		for (Documents doc : this.getDocumentList()) {
			if (doc.getTitle().equalsIgnoreCase(docTitle)) {
				docContent = doc.getContent();
				break;
			}
		}
		try {
			this.streamReportToBrowser(resp, docTitle, docContent);
		} catch (IOException e) {
			LOG.error("Error in CaseDetailPage.viewFile() method: " + e);
			// throw e;
		}
		this.getFacesContext().responseComplete();
		return "stay";
	}

	/**
	 * Helper method to view the PDF document
	 * @param response
	 * @param fileName
	 * @param content
	 * @throws IOException
	 */
	private void streamReportToBrowser(HttpServletResponse response,
			String fileName, byte[] content) throws 
			IOException {
		response.setContentType("application/x-download");
	//	response.setContentType("application/pdf");

		response.setHeader("Content-Disposition", "attachment;filename= "
				+ fileName +".pdf");
		try {
			InputStream in = new ByteArrayInputStream(content);

			ServletOutputStream saos = response.getOutputStream();
			int inputdata;
			while ((inputdata = in.read()) > -1) {
				saos.write(inputdata);
			}
			saos.close();
			in.close();
		} catch (IOException ioEx) {
			LOG.error(ioEx);
			throw new IOException(ioEx.getMessage());
		}
	}

	/**
	 * Private class used for paging the data table.
	 */
	private class ResultsDataModel extends PagedListDataModel {
		public ResultsDataModel(int pageSize) {
            super(pageSize);
        }
        
        public DataPage<FilingSearch> fetchPage(int startRow, int pageSize) {
        	return SearchResults.this.getResultsPaging(startRow, pageSize);
        }
    }
	
	/**
	 * Pages large data sets with Data Page class.
	 */
	private DataPage<FilingSearch> getResultsPaging(int startRow, int pageSize) {
		List<FilingSearch> resultSet = this.getModelFacade().search(this.searchWord);
		int dataSetSize = resultSet.size();
		this.setResultsCount(dataSetSize);
		DataPage<FilingSearch> receivedDataTableListForPage = new DataPage<FilingSearch>(dataSetSize, startRow, resultSet);
			
		return receivedDataTableListForPage;
	}

	
}
